import React, { useEffect, useState } from 'react';
import {
  Space,
  Card,
  Form,
  DatePicker,
  Input,
  Select,
  Button,
  Table,
  Modal,
  Spin,
  Tabs,
  Descriptions
} from 'antd';
import type { TabsProps } from 'antd';
import { ExportOutlined } from '@ant-design/icons';
import columns from '../../components/columns/verificationCodeColumns';
import hasAuthority from '../../components/hasAuthority';
import UserInfo from '../../components/UserInfo';
import { useStore, observer } from '../../store/verificationCode/storeHook';
import {
  booleanOptions,
  verificationCodeUsages,
  getOptionLabel
} from '../../data/statusData';

const { RangePicker } = DatePicker;

const VerificationCodeList: React.FC = () => {
  const [searchForm] = Form.useForm();
  const [editForm] = Form.useForm();

  const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
  const [activeKey, setActiveKey] = useState<string>('1');

  const store: any = useStore();

  const pagination = {
    showSizeChanger: true,
    showQuickJumper: true,
    pageSizeOptions: [10, 20, 30, 40, 50, 100],
    current: store.verificationCode.current + 1,
    pageSize: store.verificationCode.pageSize,
    total: store.verificationCode.total,
    onChange: (page: number, pageSize: number) => {
      store.verificationCode.setPageSize(pageSize);
      search(page - 1);
    },
    onShowSizeChange: (current: number, size: number) => {
      store.verificationCode.setPageSize(size);
      search(current - 1);
    }
  };

  const tabItems: TabsProps['items'] = [
    {
      key: '1',
      label: '验证码',
      forceRender: true,
      children:
        <Descriptions
          bordered
          column={1}
        >
          <Descriptions.Item label="手机">
            {store.verificationCode.record?.mobile}
          </Descriptions.Item>
          <Descriptions.Item label="验证码">
            {store.verificationCode.record?.code}
          </Descriptions.Item>
          <Descriptions.Item label="用途">
            {getOptionLabel(verificationCodeUsages, store.verificationCode.record?.usage)}
          </Descriptions.Item>
          <Descriptions.Item label="发送成功">
            {getOptionLabel(booleanOptions, store.verificationCode.record?.success + '')}
          </Descriptions.Item>
          <Descriptions.Item label="已使用">
            {getOptionLabel(booleanOptions, store.verificationCode.record?.used + '')}
          </Descriptions.Item>
          <Descriptions.Item label="创建时间">
            {store.verificationCode.record?.createdAt}
          </Descriptions.Item>
          <Descriptions.Item label="接口返回数据">
            {store.verificationCode.record?.responseBody}
          </Descriptions.Item>
          <Descriptions.Item label="错误消息">
            {store.verificationCode.record?.errorMessage}
          </Descriptions.Item>
        </Descriptions>
    },
    {
      key: '2',
      label: '用户信息',
      forceRender: true,
      children: <UserInfo userData={store.verificationCode.detail?.user || {}} />
    }
  ];

  const search = (pageNumber: number) => {
    const values = getSearchValues();
    store.verificationCode.fetchData(values.mobile, values.usage, values.success, values.used, values.createdDate, pageNumber);
  };

  const getSearchValues = () => {
    const values: any = searchForm.getFieldsValue(true);
    values.mobile = (values.mobile as string || '').trim();
    return values;
  };

  const editRecord = (record?: any) => {
    store.verificationCode.selectRecord(record);
    store.verificationCode.fetchDetail();
    setIsModalOpen(true);
  };

  const exportData = () => {
    const values = getSearchValues();
    store.verificationCode.exportData(values.mobile, values.usage, values.success, values.used, values.createdDate);
  };

  useEffect(() => {
    const values = store.verificationCode.conditions;
    store.verificationCode.fetchData(values.mobile, values.usage, values.success, values.used, values.createdDate, values.pageNumber);
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  const forbiddenComponent: React.ReactNode = hasAuthority(store, 'admin');
  if (forbiddenComponent) {
    return forbiddenComponent;
  }

  return (
    <>
      <Space
        direction="vertical"
        size={[0, 16]}
        style={{ width: '100%', padding: 16 }}
      >
        <Card
          size="small"
          title={
            <Space style={{ paddingTop: 8, paddingBottom: 16 }}>
              <Space.Compact block>
                <Button
                  disabled={store.verificationCode.loading}
                  type="primary"
                  htmlType="button"
                  onClick={() => search(0)}
                >
                  查询
                </Button>
                <Button
                  disabled={store.verificationCode.loading}
                  htmlType="button"
                  onClick={() => store.verificationCode.resetConditions(searchForm)}
                >
                  重置
                </Button>
              </Space.Compact>
              <Space.Compact block>
                <Button
                  disabled={store.verificationCode.loading}
                  htmlType="button"
                  loading={store.verificationCode.exporting}
                  onClick={() => exportData()}
                >
                  <ExportOutlined />
                  导出
                </Button>
              </Space.Compact>
            </Space>
          }
          style={{ paddingTop: 12 }}
        >
          <Form
            form={searchForm}
            name="searchForm"
            autoComplete="off"
            colon={false}
            layout="inline"
            disabled={store.verificationCode.loading}
            initialValues={store.verificationCode.conditions}
            className="search-form"
          >
            <Form.Item
              name="mobile"
              label="手机"
            >
              <Input
                autoFocus
                maxLength={ 11}
                placeholder="请输入手机"
                style={{ width: 120 }}
              />
            </Form.Item>
            <Form.Item
              name="usage"
              label="用途"
            >
              <Select
                options={verificationCodeUsages}
                style={{ width: 100 }}
              />
            </Form.Item>
            <Form.Item
              name="success"
              label="发送成功"
            >
              <Select
                options={booleanOptions}
                style={{ width: 80 }}
              />
            </Form.Item>
            <Form.Item
              name="used"
              label="已使用"
            >
              <Select
                options={booleanOptions}
                style={{ width: 80 }}
              />
            </Form.Item>
            <Form.Item
              name="createdDate"
              label="创建日期"
            >
              <RangePicker
                allowEmpty={[true, true]}
                format="YYYY-MM-DD"
                showTime={false}
              />
            </Form.Item>
          </Form>
        </Card>
        <Table
          columns={columns(booleanOptions, verificationCodeUsages, editRecord)}
          dataSource={store.verificationCode.data}
          rowKey="id"
          loading={store.verificationCode.loading}
          bordered
          scroll={{ x: 'max-content' }}
          pagination={pagination}
        />

        <Modal
          title="验证码"
          open={isModalOpen}
          maskClosable={false}
          destroyOnHidden
          forceRender
          closable
          style={{ minWidth: 320 }}
          onCancel={() => setIsModalOpen(false)}
          footer={null}
        >
          <Form
            form={editForm}
            name="editForm"
          >
            <Spin spinning={store.verificationCode.detailLoading}>
              <Tabs
                activeKey={activeKey}
                items={tabItems}
                onChange={key => setActiveKey(key)}
              />
            </Spin>
          </Form>
        </Modal>
      </Space>
    </>
  );
};

export default observer(VerificationCodeList);
